<script setup lang="ts">
import dayjs from 'dayjs'
import { useLoadMore } from 'vue-request'
import { fetchMyCouponListAPI } from '@/apis/fetchMyCouponList'
import { useUserInfoStore } from '@/store/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<Coupon>>(
  fetchData,
  { isNoMore: d => d?.list.length === d?.total },
)

// 后台删掉优惠券后，删不干净，会返回所有字段都为null的对象，需要过滤掉
const displayedDataList = computed(() => {
  return dataList.value.filter(el => el.id)
})

/* -------------------------------- Tab START ------------------------------- */
const selectedTabIndex = ref(0)
const tabs = [{ name: '我的优惠券' }, { name: '历史优惠券' }]

function handleSelectTab(item: { index: number, name: string }) {
  selectedTabIndex.value = item.index
  refresh()
}
/* --------------------------------- Tab END -------------------------------- */

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

onShow(() => refresh())
onReachBottom(() => loadMore())

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<Coupon>): Promise<LoadMoreData<Coupon>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchMyCouponListAPI(
    { page: _page.toString(), limit: '10', type: `${selectedTabIndex.value + 1}` },
    userInfoStore.userInfo!.token!,
  )

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

function handleUseCoupon(id: string) {
  router.push({
    name: 'couponQRCode',
    params: { id },
  })
}

function handleTapBottomButton() {
  router.replace({
    name: 'couponList',
  })
}
</script>

<template>
  <view class="min-h-screen bg-#F8F8F8">
    <view class="sticky top-0 z-10 w-full bg-white">
      <uv-tabs
        :current="selectedTabIndex"
        :list="tabs"
        line-color="#4999F7"
        :active-style="{ color: '#4999F7', fontWeight: '600' }"
        :inactive-style="{ color: '#848484' }"
        :scrollable="false"
        @change="handleSelectTab"
      />
    </view>
    <Spacer height="40" />
    <view v-if="displayedDataList.length > 0" class="px-24rpx">
      <CouponItem
        v-for="item in displayedDataList"
        :id="item.coupon_num"
        :key="item.id"
        :name="item.name"
        :price="item.complete_money"
        :discount-rate="item.discount?.toString()"
        :type="item.type"
        :minisum="item.money"
        :classificate="item.classificate"
        :expired="Boolean(item.is_expire)"
        :validated="Boolean(item.status - 1)"
        :period="{
          start: dayjs(item.validate_start_time!).format('YYYY.MM.DD'),
          end: dayjs(item.validate_end_time!).format('YYYY.MM.DD'),
        }"
        :tip="item.explain || ''"
        :owned="true"
        @use="handleUseCoupon(item.id?.toString())"
      />
      <!-- 加载更多 -->
      <uv-load-more v-if="displayedDataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
      <Spacer height="240" />
    </view>
    <PageDefault v-else>
      暂无优惠券
    </PageDefault>
  </view>
  <button class="fixed bottom-0 z-2 h-128rpx w-screen flex items-center justify-center rounded-0 bg-#4999F7 text-32rpx text-white leading-45rpx x-center" @tap="handleTapBottomButton">
    <image class="h-30rpx w-44rpx" src="@/static/images/coupon_single_color.png" />
    <Spacer width="16" />
    领券中心
  </button>
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'myCouponList'
style:
  navigationBarTitleText: '我的优惠券'
layout: 'custom'
</route>
